package com.sync.data.common.util;

import org.springframework.lang.NonNull;

import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;

public class SetValueUtils {

    /**
     * set值防止为有空值
     * @param supplier
     * @param consumer
     * @param <T>
     * @example SetValueUtils.setIfNotEmpty(speakerSchema::getType,hcpVm::setSpeakerType);
     */
    public static <T> boolean setIfNotEmpty(Supplier<T> supplier, Consumer<T> consumer) {
        try {
            T  value = supplier.get();
            if (isNonEmpty(value)) {
                consumer.accept(value);
                return true;
            }else {
                return false;
            }
        }catch (Exception ignored) {
            return false;
        }
    }

    public static <T> void setIfNotEmpty(Supplier<T> supplier,Consumer<T> consumer,@NonNull T defaultValue) {
        if (!setIfNotEmpty(supplier,consumer)) {
            consumer.accept(defaultValue);
        }
    }

    private static boolean isNonEmpty(Object value) {
        if (value == null) {
            return false;
        }
        if (value instanceof String) {
            String strValue = (String) value;
            return !strValue.trim().isEmpty();
        } else if (value instanceof Collection) {
            return !((Collection<?>) value).isEmpty();
        } else if (value instanceof Map) {
            return !((Map<?, ?>) value).isEmpty();
        } else if (value instanceof Object[]) {
            return ((Object[]) value).length > 0;  // 检查数组非空
        }else if (value instanceof Optional) {
            return ((Optional<?>) value).isPresent();
        }
        return true;
    }

    public static boolean setStrFromList(Supplier<Iterable<String>> supplier, Consumer<String> consumer){
        try {
            Iterable<String> value = supplier.get();
            consumer.accept(String.join(",", value));
            return true;
        }catch (Exception ignored) {
            return false;
        }
    }

}
